﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace Athena.Tracing
{
    public class SingleThreadWatcher
    {
        private readonly static Dictionary<string, TracingWatcherInfo> _stopwatchs = new Dictionary<string, TracingWatcherInfo>();
        private static int _timers = 0;
        private static long _sumValue = 0;

        public static void Start(string id)
        {
            _stopwatchs.Add(id, new TracingWatcherInfo());
        }

        public static void Injection(string id, string content)
        {
            if (_stopwatchs.TryGetValue(id, out TracingWatcherInfo tracingWatcherInfo))
            {
                tracingWatcherInfo.ContentBuilder.AppendLine($"{content}.目前为止执行时间 {tracingWatcherInfo.Stopwatch.Elapsed.TotalMilliseconds } ms");
            }
        }

        public static void Stop(string id, Func<Stopwatch, bool> filter = null)
        {
            if (_stopwatchs.TryGetValue(id, out TracingWatcherInfo tracingWatcherInfo))
            {
                var stopwatch = tracingWatcherInfo.Stopwatch;
                stopwatch.Stop();
                _stopwatchs.Remove(id);
                Task.Factory.StartNew(() =>
                {
                    //var id2 = Thread.CurrentThread.ManagedThreadId;
                    if (stopwatch.Elapsed.TotalMilliseconds < 0.2)
                    {
                        Interlocked.Add(ref _sumValue, (long)(stopwatch.Elapsed.TotalMilliseconds * 1000 * 1000));
                        Interlocked.Increment(ref _timers);
                        var avg = (_sumValue / _timers / 1000 / 1000m).ToString("f4");
                        tracingWatcherInfo.ContentBuilder.AppendLine($"本次执行时间 {stopwatch.Elapsed.TotalMilliseconds } ms");
                        tracingWatcherInfo.ContentBuilder.AppendLine($" 当前：count:[{_timers}], avg:[{avg}] ms");
                        Console.WriteLine(tracingWatcherInfo.ContentBuilder.ToString());
                    }
                });
            }
        }

        public static void Reset()
        {
            _timers = 0;
            _sumValue = 0;
            _stopwatchs.Clear();
        }

    }
}